package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utis.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    ItemClient itemClient;
    @Autowired
    IOrderDetailService orderDetailService;
    @Autowired
    UserClient userClient;
    @Autowired
    OrderLogisticsService logisticsService;
    @Transactional
    @Override
    public Long creatOrder(RequestParams requestParams) {

        //从item服务 根据ID查商品item
        Item item = itemClient.getById(requestParams.getItemId());
        //根据商品数量和商品单价算出总价
        long totalFee = item.getPrice() * requestParams.getNum();
        Order order = new Order();
        //订单状态未支付
        order.setStatus(1);
        order.setTotalFee(totalFee);
        //从threadlocal获取id
        order.setUserId(UserHolder.getUser());
        order.setPaymentType(requestParams.getPaymentType());
        this.save(order);
//    （7）将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setName(item.getName());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setNum(requestParams.getNum());
        orderDetail.setItemId(item.getId());
        orderDetail.setImage(item.getImage());
        orderDetail.setOrderId(order.getId());
        orderDetail.setPrice(item.getPrice());
        orderDetailService.save(orderDetail);
//    （8）将user-service的根据id查询地址接口封装为FeignClient
//    （9）根据addressId查询user-service服务，获取地址信息
        Address addressById = userClient.findAddressById(requestParams.getAddressId());
//    （10）将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(addressById,orderLogistics);
        orderLogistics.setOrderId(order.getId());
        logisticsService.save(orderLogistics);
//    （11）在item-service提供减库存接口，并编写FeignClient
//    （12）调用item-service的减库存接口
        try {
            itemClient.updateStock(requestParams.getItemId(),requestParams.getNum());
        } catch (Exception exception) {
            throw new RuntimeException("库存不足");
        }

        return order.getId();
    }
}
